package utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;


public class SendEmailUtils {
    public static void sendEmail(String receptionPeopleEmail, String authCode) throws MessagingException, GeneralSecurityException {
        // 获取需要的配置信息
        final String host = PropertiesUtils.getPropertiesValue("/email.properties", "email.host");
        final String smtp = PropertiesUtils.getPropertiesValue("/email.properties", "email.smtp");
        final String auth = PropertiesUtils.getPropertiesValue("/email.properties", "email.auth");
        final String enable = PropertiesUtils.getPropertiesValue("/email.properties", "email.enable");
        final String sendPeopleEmail = PropertiesUtils.getPropertiesValue("/email.properties", "email.sendPeopleEmail");
        final String authorizationCode = PropertiesUtils.getPropertiesValue("/email.properties", "email.authorizationCode");
        //创建一个配置文件并保存
        Properties properties = new Properties();

        properties.setProperty("mail.host", host);

        properties.setProperty("mail.transport.protocol", smtp);

        properties.setProperty("mail.smtp.auth", auth);


        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", enable);
        properties.put("mail.smtp.ssl.socketFactory", sf);

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sendPeopleEmail, authorizationCode);
            }
        });

        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = session.getTransport();

        //连接服务器
        transport.connect(host, sendPeopleEmail, authorizationCode);

        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);

        //邮件发送人
        mimeMessage.setFrom(new InternetAddress(sendPeopleEmail));

        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(receptionPeopleEmail));

        //邮件标题
        mimeMessage.setSubject("简易电子超市");

        //邮件内容
        mimeMessage.setContent("您的验证码是:" + authCode + ",打死也不要告诉别人哦!", "text/html;charset=UTF-8");

        //发送邮件
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

        //关闭连接
        transport.close();
    }

    /**
     * 生成6为数字验证码
     * @return
     */
    public static String authCode() {
        long codeL = System.nanoTime();
        String codeStr = Long.toString(codeL);
        return codeStr.substring(codeStr.length() - 6);
    }
}
